


import 'dart:collection';
import 'dart:core';
import 'dart:math';

import 'package:flutter/src/foundation/change_notifier.dart';

import 'package:rms_mobile_client/StateManagement/ModelProvider.dart';

import 'ModelProvider.dart';

class MyObservableList<T> extends ListMixin<T> with Model {
  var _list = List<T>();
  @override
  int get length => _list.length;
  @override
  set length(int len) => _list.length = len;

  @override
  operator [](int index) {
    return _list[index];
  }

  @override
  void operator []=(int index, value) {
    _unRegisterHandler(_list[index]);
    _list[index] = value;
    _registerHandler(value);
  }

  @override
  void add(T element) {
    super.add(element);
    applyChanges();
  }

  @override
  void addAll(Iterable<T> iterable) {
    super.addAll(iterable);
    applyChanges();
  }

  @override
  void insert(int index, T element) {
    super.insert(index, element);
    applyChanges();
  }

  @override
  void insertAll(int index, Iterable<T> iterable) {
    super.insertAll(index, iterable);
    applyChanges();
  }

  @override
  bool remove(Object element) {
    _unRegisterHandler(element);
    applyChanges();
    return super.remove(element);
  }

  @override
  T removeAt(int index) {
    _unRegisterHandler(this[index]);
    applyChanges();
    return super.removeAt(index);
  }

  @override
  void removeWhere(bool Function(T element) test) {
    this.where(test).forEach(_unRegisterHandler);
    applyChanges();
    super.removeWhere(test);
  }

  @override
  T removeLast() {
    var result = super.removeLast();
    _unRegisterHandler(result);
    applyChanges();
    return result;
  }

  void _registerHandler(T element){
    if (element == null) return;
    (element as Model).notifier.addListener(_handler);
  }

  void _unRegisterHandler(T element){
    if (element == null) return;
    (element as Model).notifier.removeListener(_handler);
  }

  void _handler(){
    applyChanges();
  }
}

